<template>
	<transition name="slide-fade">
		<div class="user-info-mask">
			<div class="user-info-box">
				<div class="user-info-content">
					<!-- 头部操作栏 -->
					<div class="action-header">
						<div class="empty-space"></div>
						<div class="title">用户信息</div>
						<div class="close-btn" @click="handleClose">
							<el-icon><Close /></el-icon>
						</div>
					</div>
					
					<!-- 头像和基本信息 -->
					<div class="user-header">
						<div class="avatar-box">
							<head-image 
								:url="localUserInfo?.headImage" 
								:name="localUserInfo?.nickName"
								:size="90">
							</head-image>
						</div>
						<div class="user-name">{{ localUserInfo?.nickName || '未知用户' }}</div>
						<div class="user-id">ID: {{ localUserInfo?.chatNo || '未知' }}</div>
					</div>

					<!-- 用户信息 -->
					<div class="user-detail">
						<div class="info-item">
							<div class="label">备注：</div>
							<template v-if="!isEditing">
								<div class="value">{{ displayRemarkName }}</div>
								<el-tooltip content="编辑备注" placement="top" :enterable="false">
									<el-icon class="edit-icon" @click="startEdit"><EditPen /></el-icon>
								</el-tooltip>
							</template>
							<template v-else>
								<div class="edit-remark-wrapper">
									<el-input 
										v-model="editingRemarkName" 
										size="small"
										ref="remarkInput"
										class="remark-input">
									</el-input>
									<div class="edit-buttons">
										<el-button size="small" type="primary" @click="saveRemarkName">确认</el-button>
										<el-button size="small" @click="cancelEdit">取消</el-button>
									</div>
								</div>
							</template>
						</div>
						<div class="info-item">
							<span class="label">性别:</span>
							<span class="value">
								<el-tag size="small" :type="localUserInfo?.sex === 0 ? 'info' : 'danger'" effect="light" round>
									{{ localUserInfo?.sex === 0 ? '男' : '女' }}
								</el-tag>
							</span>
						</div>
						<div class="info-item signature-item">
							<span class="label">签名:</span>
							<span class="value signature">{{ localUserInfo?.signature || '这个人很懒，什么都没写~' }}</span>
						</div>
					</div>

					<!-- 操作按钮 -->
					<div class="action-buttons">
						<el-button 
							type="primary" 
							size="large"
							@click="onSendMessage"
							class="action-btn send-btn">
							<el-icon><ChatDotRound /></el-icon> 发消息
						</el-button>
						<el-button 
							type="danger" 
							size="large"
							@click="onDeleteFriend"
							class="action-btn delete-btn">
							<el-icon><Delete /></el-icon> 删除好友
						</el-button>
					</div>
				</div>
			</div>
		</div>
	</transition>
</template>

<script>
	import HeadImage from './HeadImage.vue'
	import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
	import { useStore } from 'vuex'
	import { useRouter } from 'vue-router'
	import { ref, onMounted, onBeforeUnmount, nextTick, getCurrentInstance, computed, watch } from 'vue'
	import axios from 'axios'

	export default {
		name: 'UserInfo',
		components: {
			HeadImage,
		},
		props: {
			user: {
				type: Object,
				required: true,
				default: () => ({})
			}
		},
		emits: ['close', 'refresh-friend-list'],
		setup(props, { emit }) {
			const store = useStore()
			const router = useRouter()
			const remarkInput = ref(null)
			const isEditing = ref(false)
			const editingRemarkName = ref('')
			const remarkName = ref('')
			
			// 本地状态来显示备注，避免直接修改props
			const localUserInfo = ref({...props.user})
			
			// 监听props变化，更新本地状态
			watch(() => props.user, (newVal) => {
				localUserInfo.value = {...newVal}
			}, { immediate: true, deep: true })
			
			// 计算属性: 显示的备注名
			const displayRemarkName = computed(() => {
				return localUserInfo.value.userName || '未设置'
			})
			
			// 获取应用实例以访问全局属性
			const { proxy } = getCurrentInstance()

			const handleKeyDown = (e) => {
				if (e.key === 'Escape' || e.keyCode === 27) {
					handleClose()
				}
			}

			const handleClose = () => {
				if (isEditing.value) {
					cancelEdit()
				}
				store.commit('hideUserInfoBox')
				emit('close')
			}

			const onSendMessage = () => {
				const chat = {
					type: 'PRIVATE',
					targetId: props.user.userId,
					showName: props.user.userName || props.user.nickName,
					headImage: props.user.headImage
				}
				
				store.commit('hideUserInfoBox')
				emit('close')
				
				store.commit('openChat', chat)
				store.commit('saveToStorage')
				store.commit('getactiveChat', props.user.userId)
				
				nextTick(() => {
					router.push('/home/chat')
				})
			}

			const onDeleteFriend = () => {
				if (!props.user || !props.user.userId || !props.user.nickName) {
					ElMessage.error('无效的好友信息')
					return
				}
				
				// 设置更高的z-index防止被遮挡
				ElMessageBox.confirm(`确认删除'${props.user.nickName}',并清空聊天记录吗?`, '确认解除?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'user-info-message-box',
					appendToBody: true,  // 添加到body，避免被遮挡
					closeOnClickModal: false,  // 点击遮罩层不关闭
					modalAppendToBody: true,  // 遮罩层添加到body
					lockScroll: true  // 锁定滚动
				}).then(() => {
					const loading = ElLoading.service({
						lock: true,
						text: '正在删除...',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					
					proxy.$http({
						url: `/friend/delete/${props.user.userId}`,
						method: 'delete'
					}).then(() => {
						ElMessage.success('删除好友成功')
						store.commit('hideUserInfoBox')
						emit('close')
						store.commit('removeFriend', props.user.userId)
						store.commit('removePrivateChat', props.user.userId)
						loading.close();
						//重新加载好友列表
						store.dispatch('loadFriend').then(() => {
							emit('refresh-friend-list')
						}).catch(err => {
							console.error('刷新好友列表失败:', err)
						})
					}).catch((error) => {
						loading.close()
						console.error('删除好友失败:', error)
						ElMessage.error('删除好友失败，请重试')
					})
				}).catch(() => {
					// 用户取消删除操作
				})
			}

			const startEdit = () => {
				editingRemarkName.value = props.user.remark || ''
				isEditing.value = true
				nextTick(() => {
					remarkInput.value?.focus()
				})
			}

			const cancelEdit = () => {
				isEditing.value = false
				editingRemarkName.value = ''
			}

			const saveRemarkName = () => {
				if (!editingRemarkName.value.trim()) {
					ElMessage.warning('备注名不能为空')
					return
				}
				
				if (editingRemarkName.value === props.user.remark) {
					isEditing.value = false
					return
				}
				
				let data = {
					remark: editingRemarkName.value.trim(),
					friendId: props.user.userId
				}
				
				// 使用全局代理访问$http
				proxy.$http({
					url: "/friend/setting",
					method: 'post',
					data: data
				}).then(() => {
					// 更新修改状态
					const newRemark = editingRemarkName.value.trim()
					
					// 更新本地状态显示
					localUserInfo.value = {
						...localUserInfo.value,
						remark: newRemark,
						userName: newRemark
					}
					// 刷新好友列表
					store.dispatch('loadFriend').then(() => {
						emit('refresh-friend-list')
						ElMessage.success('备注修改成功')
					}).catch(err => {
						console.error('刷新好友列表失败:', err)
					})
					
					isEditing.value = false
				}).catch((error) => {
					console.log(error)
					ElMessage.error('修改失败，请重试')
				})
			}

			onMounted(() => {
				window.addEventListener('keydown', handleKeyDown)
			})

			onBeforeUnmount(() => {
				window.removeEventListener('keydown', handleKeyDown)
			})

			return {
				remarkInput,
				isEditing,
				editingRemarkName,
				remarkName,
				localUserInfo,
				displayRemarkName,
				handleClose,
				onSendMessage,
				onDeleteFriend,
				startEdit,
				saveRemarkName,
				cancelEdit
			}
		}
	}
</script>

<style lang="scss" scoped>
.user-info-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	justify-content: center;
	align-items: center;
}

.user-info-box {
	position: relative;
	width: 340px;
	padding: 0;
	background: #fff;
	border-radius: 16px;
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12), 0 5px 15px rgba(0, 0, 0, 0.08);
	overflow: hidden;
	transition: all 0.3s ease;
	will-change: transform, opacity;
	backface-visibility: hidden;
	
	&:hover {
		box-shadow: 0 12px 36px rgba(0, 0, 0, 0.15), 0 6px 18px rgba(0, 0, 0, 0.1);
	}
	
	.action-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 14px 16px;
		background: #f8f9fa;
		border-bottom: 1px solid #eee;
		
		.title {
			font-size: 16px;
			font-weight: 500;
			color: #333;
		}
		
		.empty-space, .close-btn {
			width: 24px;
			height: 24px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.close-btn {
			cursor: pointer;
			border-radius: 50%;
			color: #606266;
			transition: all 0.2s;
			
			&:hover {
				background-color: rgba(0, 0, 0, 0.05);
				color: #333;
			}
		}
	}

	.user-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 24px 0 12px;
		background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-5));
		position: relative;
		border-bottom: none;

		.avatar-box {
			margin-bottom: 16px;
			border: 4px solid rgba(255, 255, 255, 0.85);
			border-radius: 50%;
			overflow: hidden;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		}

		.user-name {
			font-size: 20px;
			font-weight: 600;
			color: #333;
			margin-bottom: 6px;
		}

		.user-id {
			font-size: 13px;
			color: #666;
			opacity: 0.85;
			margin-bottom: 8px;
		}
	}

	.user-detail {
		padding: 18px 20px;
		background: #fff;
		border-radius: 12px 12px 0 0;
		margin-top: -12px;
		position: relative;
		box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.05);

		.info-item {
			margin-bottom: 16px;
			line-height: 1.5;
			font-size: 14px;
			display: flex;
			align-items: center;
			position: relative;
			
			.label {
				color: #606266;
				width: 50px;
				flex-shrink: 0;
				font-weight: 500;
			}

			.value {
				flex: 1;
				color: #303133;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: normal;
				word-break: break-word;
				padding-right: 24px;
			}
			
			.edit-icon {
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				cursor: pointer;
				color: var(--el-color-primary);
				font-size: 16px;
				transition: all 0.2s ease;
				opacity: 0.7;
				
				&:hover {
					opacity: 1;
					transform: translateY(-50%) scale(1.15);
				}
			}
			
			.remark-input {
				width: 100%;
				max-width: 240px;
			}

			.edit-remark-wrapper {
				display: flex;
				flex-direction: column;
				width: 100%;
				gap: 8px;

				.edit-buttons {
					display: flex;
					gap: 8px;
				}
			}
		}
		
		.signature-item {
			margin-bottom: 0;
			
			.signature {
				font-style: italic;
				font-size: 13px;
				color: #606266;
				line-height: 1.5;
				max-height: 60px;
				overflow-y: auto;
			}
		}
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		padding: 16px 20px;
		background: #f8f9fa;
		border-top: 1px solid #eee;

		.action-btn {
			flex: 1;
			margin: 0 6px;
			padding: 10px 0;
			font-size: 14px;
			border-radius: 10px;
			transition: all 0.3s cubic-bezier(0.25, 1, 0.5, 1);
			
			&:deep(.el-icon) {
				margin-right: 6px;
				font-size: 16px;
				vertical-align: middle;
				transition: transform 0.3s ease;
			}
			
			&:hover {
				transform: translateY(-2px);
				
				&:deep(.el-icon) {
					transform: scale(1.15);
				}
			}
			
			&.send-btn {
				background-color: var(--el-color-primary);
				border-color: var(--el-color-primary);
				color: white;
				
				&:hover {
					background-color: var(--el-color-primary-dark-2);
					box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
				}
				
				&:active {
					transform: translateY(-1px);
				}
			}
			
			&.delete-btn {
				background-color: var(--el-color-danger);
				border-color: var(--el-color-danger);
				color: white;
				
				&:hover {
					background-color: var(--el-color-danger-dark-2);
					box-shadow: 0 6px 16px rgba(245, 108, 108, 0.3);
				}
				
				&:active {
					transform: translateY(-1px);
				}
			}
		}
	}
}
</style>

<style lang="scss">
/* 定义过渡动画 */
.slide-fade-enter-active {
	animation: popup-in 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}

.slide-fade-leave-active {
	animation: popup-out 0.2s cubic-bezier(0.47, 0, 0.745, 0.715) forwards;
}

@keyframes popup-in {
	0% {
		opacity: 0;
		transform: translate(-50%, -48%) scale(0.9);
		box-shadow: 0 0 0 rgba(0, 0, 0, 0);
	}
	70% {
		opacity: 1;
		transform: translate(-50%, -51%) scale(1.04);
	}
	100% {
		opacity: 1;
		transform: translate(-50%, -50%) scale(1);
		box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12), 0 5px 15px rgba(0, 0, 0, 0.08);
	}
}

@keyframes popup-out {
	0% {
		opacity: 1;
		transform: translate(-50%, -50%) scale(1);
	}
	100% {
		opacity: 0;
		transform: translate(-50%, -48%) scale(0.95);
		box-shadow: 0 0 0 rgba(0, 0, 0, 0);
	}
}

/* 确保弹框不被遮挡 */
.user-info-message-box {
	z-index: 99999 !important;
}

/* 确保全局消息框和加载样式不被遮挡 */
body {
	.el-message-box__wrapper {
		z-index: 99999 !important;
	}
	
	.el-message {
		z-index: 99999 !important;
	}
	
	.el-loading-mask {
		z-index: 99999 !important;
	}
	
	.el-overlay {
		z-index: 99998 !important;
	}
}
</style>